<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/7/17
 * Time: 10:51
 */
namespace app\api\controller;
use think\Db;
class Apilogin extends Common
{
    /**
     * 快捷登录
     * @return bool
     * 参数：phone，code
     * 返回：0参数错误，1手机号为空，2验证码为空， 3手机号格式不正确，4验证码错误，5验证码超时， 6验证码已使用
     *      7该账号已被冻结， 200成功
     */
    public  function phoneLogin(){
        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['code'])){
            return json_encode(['status'=>0,'msg'=>'参数错误'], 256);
        }
        $phone = trim($_POST['phone'], ' ');
        $code = trim($_POST['code'],' ');
        if($phone == ''){
            return $this->apiError(1, '请输入手机号');
        }
        if($code == ''){
            return $this->apiError(2, '请输入验证码');
        }
        if(!preg_match("/^1[34578]\d{9}$/", $phone)){
            return json_encode(['status'=>3,'msg'=>'请填写正确的手机号码'], 256);
        }
        //=============================================
        $res = Db::table('up_phonecode')
            ->where('phone',$phone)
            ->order('time2 desc')
            ->limit(1)
            ->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>4,'msg'=>'验证码错误'], 256);
        }
        $now = time();
        if($now - $res['time2'] >= 901){
            return json_encode(['status'=>5,'msg'=>'验证码超时'], 256);
        }
        if($res['status']==1){
            return json_encode(['status'=>6,'msg'=>'验证码已使用'], 256);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){//如果没有该用户，快捷登录时自动注册
            $token = md5(date('YmdHis').rand(100000,999999));
            $data = [
                'user_time' => date('Y-m-d H:i:s'),
                'user_token' => $token,
                'user_phone' => $phone,
                'user_username' => $phone,
                'user_attestation' =>1
            ];
            $user_id = Db::name('u_user')->insertGetId($data);
            $username = Db::table('up_u_user')->where('user_id',$user_id)->find();
            Db::table('up_phonecode')->where('id',$res['id'])->update(['status'=>1]);
//            return $this->apiSuccess($username);
            return json_encode(['status'=>200, 'msg'=>$username]);
        }else{
            if($username['user_status'] == 2){
                return json(['status'=>7,'msg'=>'该账号已被冻结']);
            }else{
                //更新token
                $token = md5(date('YmdHis') . rand(100000,999999));
                $last_login_time = time();//最后登录时间
                Db::table('up_u_user')->where('user_phone',$phone)->update(['user_token'=>$token, 'last_login_time'=>$last_login_time]);
                $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
                Db::table('up_phonecode')->where('id',$res['id'])->update(['status'=>1]);
                return json_encode(['status'=>200,'msg'=>$username]);
            }
        }
    }
    
    /**
     * 账号密码登录
     * @return bool
     * 参数：账号、密码
     * 返回值：0请输入手机号，1手机号码错误，2密码格式错误，3没有此用户，4密码错误，5成功  6请输入密码
     */
    public  function userLogin(){
        header("Access-Control-Allow-Origin:*");
        extract(input());
        if($phone == ''){
            return json(['status'=>0,'msg'=>'请输入手机号']);
        }
        if($pass == ''){
            return json(['status'=>6,'msg'=>'请输入密码']);
        }
        if(preg_match("/^1[3456789]\d{9}$/", $phone)){
            if(empty($pass) || !isset($pass)){
                return json(['status'=>2,'msg'=>'请填写正确的密码']);
            }else{
                $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
                if(empty($username)){
                    return json(['status'=>3,'msg'=>'没有此用户']);
                }else{
                    if($username['user_password'] != md5($pass)){
                        return json(['status'=>4,'msg'=>'密码错误']);
                    }
                    if($username['user_status'] == 2){
                        return json(['status'=>5,'msg'=>'该账号已被冻结']);
                    }
                    //更新token
                    $token = md5(date('YmdHis') . rand(100000,999999));
                    $last_login_time = time();//最后登录时间
                    Db::table('up_u_user')->where('user_phone',$phone)->update(['user_token'=>$token, 'last_login_time'=>$last_login_time]);
                    $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
                    return json(['status'=>200,'msg'=>$username]);
                }
            }
        }else{
            return json(['status'=>1,'msg'=>'手机号错误']);
        }
    }
    
    /**
     * 微信||QQ||微博第一次登录第一步
     * wqtoken，phone，code，name，image
     * type：1微信   2QQ  3微博
     * @return string
     */
    public  function wqFirstLogin()
    {
        header("Access-Control-Allow-Origin:*");
        $wqtoken = $_POST['wqtoken'];
        $type = $_POST['type'];
        if($type == 1){
            $field = '_wx_';
        }elseif($type == 2){
            $field = '_qq_';
        }else{
            $field = '_wb_';
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $name = $_POST['name'];
        $image = $_POST['image'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        if($code==''){
            return json_encode(['status'=>4,'msg'=>'有未填项，请检查']);
        }
        //=============================================
        $res = Db::table('up_phonecode')
            ->where('phone',$phone)
            ->order('time2 desc')
            ->limit(1)
            ->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 901){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        Db::table('up_phonecode')->where('id',$res['id'])->update(['status'=>1]);
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            //第一次用微信绑定好了，第二次又用另一个微信绑定时判断（qq同理）
            if($username["user{$field}token"]){
                return json_encode(['status'=>3,'msg'=>'已绑定同类型第三方了']);
            }
            //=========end==============
            $token = md5(date('YmdHis').rand(100000,999999));
            $data = array();
            $data['user_token'] = $token;
            $data['user'.$field.'token'] = $wqtoken;
            $data['user'.$field.'nickname'] = $name;
            $data['user'.$field.'image'] = $image;
            $data['last_login_time'] = time();
            $user = Db::table('up_u_user')->where('user_phone',$phone)->field('user_username,user_image')->find();
            if(!$user['user_username']){
                $data['user_username'] = $name;
            }
            if(!$user['user_image']){
                $data['user_image'] = $image;
            }
            $res = Db::table('up_u_user')->where('user_phone',$phone)->update($data);
            $res2 = Db::table('up_u_user')->where('user_phone',$phone)->find();
            if($res){
                return json_encode(['status'=>200,'msg'=>$res2]);
            }else{
                return json_encode(['status'=>3,'msg'=>'绑定失败']);
            }
        }else{
            $token = md5(date('YmdHis').rand(100000,999999));
            $data = array();
            $data['user_token'] = $token;
            $data['user'.$field.'token'] = $wqtoken;
            $data['user'.$field.'nickname'] = $name;
            $data['user'.$field.'image'] = $image;
            $data['last_login_time'] = time();
            $data['user_time'] = date('Y-m-d H:i:s');
            $data['user_phone'] = $phone;
            $data['user_image'] = $image;//用户名字和头像同步一下
            $data['user_username'] = $name;//
//        $data['user_app_count'] = $this->getAcount();
//            $data['user_password'] = md5($pass);
            $id = Db::name('u_user')->insertGetId($data);
            if($id){
                $user = Db::table('up_u_user')
                    ->where('user_id',$id)
                    ->find();
                return json_encode(['status'=>200,'msg'=>$user]);
            }else{
                return json_encode(['status'=>5,'msg'=>'生成登录数据失败']);
            }
        }
    }
    
    /**
     * 微信||qq||微博第一次登录第二步
     * wqtoken，phone，name，image，type
     * @return string
     */
    public  function wqFirstLoginTwo()
    {
        header("Access-Control-Allow-Origin:*");
        $wqtoken = $_POST['wqtoken'];
        $type = $_POST['type'];
        if($type == 1){
            $field = '_wx_';
        }elseif($type == 2){
            $field = '_qq_';
        }else{
            $field = '_wb_';
        }
        $phone = $_POST['phone'];
        $name = $_POST['name'];
        $image = $_POST['image'];
        $pass = $_POST['pass'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json_encode(['status'=>3,'msg'=>'绑定步骤出错']);
        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $data = array();
        $data['user_time'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        $data['user_phone'] = $phone;
        $data['user'.$field.'token'] = $wqtoken;
        $data['user'.$field.'nickname'] = $name;
        $data['user'.$field.'image'] = $image;
        $data['user_image'] = $image;//用户名字和头像同步一下
        $data['user_username'] = $name;//
//        $data['user_app_count'] = $this->getAcount();
        $data['user_password'] = md5($pass);
        $id = Db::name('u_user')->insertGetId($data);
        if($id){
            $user = Db::table('up_u_user')
                ->where('user_id',$id)
                ->find();
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>5,'msg'=>'生成登录数据失败']);
        }
    }
    
    /**
     * 微信||QQ||微博
     * wqtoken,type(1是微信，2是qq，3是微博)
     * @return string
     */
    public  function wqLogin()
    {
        header("Access-Control-Allow-Origin:*");
        $wxtoken = $_POST['wqtoken'];
        $type = $_POST['type'];
        if($type == 1){
            $field = 'user_wx_token';
        }elseif($type == 2){
            $field = 'user_qq_token';
        }else{
            $field = 'user_wb_token';
        }
        $username = Db::table('up_u_user')->where($field, $wxtoken)->find();
        if (!empty($username)) {
            $token = md5(date('YmdHis') . rand(100000, 999999));
            $res = Db::table('up_u_user')->where($field, $wxtoken)->update(['user_token' => $token]);
            if ($res) {
                //===禁用和启用====
                if($username['user_status'] != 1){
                    return json_encode(['status' => 0, 'msg' => '对不起，您无权登录，请联系客服']);
                }
                //======end======
                $user = Db::table('up_u_user')->where($field, $wxtoken)->find();
                return json_encode(['status' => 200, 'msg' => $user]);
            } else {
                return json_encode(['status' => 3, 'msg' => '数据库出错']);
            }
        }else{
            return json_encode(['status' => 4, 'msg' => '查无此人']);
        }
        
    }
    
    /**
     * 发送验证码
     * @return \think\response\Json|void
     * phone：填写的手机号
     * type：   1 验证手机号   2 更换绑定的手机号
     */
    public function getPhoneCode(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        if(trim($params['phone'], ' ') == ''){
            return $this->apiError(0, '请输入手机号');
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $params['phone'])){
            return $this->apiError(1, '请输入正确格式的手机号');
        }
        $userInfo = Db::table('up_u_user')->where('user_phone', $params['phone'])->find();
        if(empty($userInfo) && $params['type'] == 1){//验证手机号
            return $this->apiError(2, '没有此手机号的用户');
        }
        if(!empty($userInfo) && $params['type'] == 2){//更换绑定的手机号
            return $this->apiError(3, '此号码已被绑定');
        }
        if(!empty($userInfo) && $params['type'] == 3){//第三方登录时绑定手机号
            if($params['types'] == 1){
                $field = '_wx_';
            }elseif($params['types'] == 2){
                $field = '_qq_';
            }else{
                $field = '_wb_';
            }
            if($userInfo["user{$field}token"]){
                return $this->apiError(4, '此号码已被绑定');
            }
        }
        $startTime = strtotime(date('Y-m-d 00:00:00'));//当天的起始时间
        $endTime = strtotime(date('Y-m-d 23:59:59'));//当天的结束时间
        $where = [];
        $where['phone'] = $params['phone'];
        $where['time2'] = ['between', [$startTime, $endTime]];
        $num = Db::table('up_phonecode')->where($where)->count('id');
        if($num == 5){
            return $this->apiError(10, '短信验证码今日已发送5次，请明天再来');
        }
        $code = GetRandCode();//6位数验证码
        $templateid = config('yzx')['templateid'];
        $sendres = YzxSms($templateid, $code, $params['phone'], $params['user_id']);//发送验证码
        if($sendres['code'] != '00000'){//发送不成功
            return json(['status'=>11,'msg'=>$sendres['msg']]);
        }else{
            $data = [
                'phone' => $params['phone'],//发送的手机号
                'code' => $code,//加密后的验证码
                'time2' => time(),//验证码发送的时间戳
            ];
            $res = Db::table('up_phonecode')->insert($data);
            if(!$res){
                return json(['status' => 12, 'msg' => '数据库操作失败']);
            }
            return json(['status' => 200, 'msg' => $code]);
        }
    }
    
    /**
     * 修改密码
     * @return \think\response\Json
     * oldPassword：旧密码
     * newPassword：新密码
     * user_id：用户ID
     */
    public function updatePassword(){
        $params = input('param.');
        $oldPassword = trim($params['oldPassword']);
        $newPassword = trim($params['newPassword']);
        if($oldPassword == ''){
            return json(['status'=>1, 'msg'=>'请输入旧密码']);
        }
        if($newPassword == ''){
            return json(['status'=>2, 'msg'=>'请输入新密码']);
        }
        $oldPW = Db::table('up_u_user')->where('user_id', $params['user_id'])->find();
        if(md5($oldPassword) != $oldPW['user_password']){
            return json(['status'=>3, 'msg'=>'旧密码错误，请重新输入']);
        }
        $updatePassword['user_password'] = md5($newPassword);
        $res = Db::table('up_u_user')->where('user_id', $params['user_id'])->update($updatePassword);
        if($res){
            return json(['status'=>4, 'msg'=>'修改成功']);
        }else{
            return json(['status'=>5, 'msg'=>'修改失败']);
        }
    }
    
    /**
     * 修改密码
     * @return \think\response\Json
     * newPassword1：第一次输入的密码
     * newPassword2：第二次输入的密码
     * user_id：用户ID
     */
    public function setPwd(){
        $params = input('param.');
        $newPassword1 = trim($params['newPassword1']);
        $newPassword2 = trim($params['newPassword2']);
        if($newPassword1 == ''){
            return json(['status'=>1, 'msg'=>'请输入密码']);
        }
        if($newPassword2 == ''){
            return json(['status'=>2, 'msg'=>'请输入确认密码']);
        }
        if($newPassword1 != $newPassword2){
            return json(['status'=>3, 'msg'=>'两次密码输入不一致']);
        }
        $updatePassword['user_password'] = md5($newPassword1);
        $res = Db::table('up_u_user')->where('user_id', $params['user_id'])->update($updatePassword);
        $userInfo = Db::table('up_u_user')->where('user_id', $params['user_id'])->find();
        if($res){
            return json(['status'=>4, 'msg'=>'设置成功', 'data'=>$userInfo]);
        }else{
            return json(['status'=>5, 'msg'=>'设置失败']);
        }
    }
    
    /**
     * 找回密码&设置登录密码
     * @return bool
     * 参数：phone,code
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，200成功
     */
    public  function forgetPass(){
        header("Access-Control-Allow-Origin:*");
        extract(input());
        if(!isset($phone) || !isset($code)){
            return json(['status'=>0,'msg'=>'参数错误']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        if($newpass == '' || $code == ''){
            return json(['status'=>2,'msg'=>'有未填项']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            return json(['status'=>3,'msg'=>'没有此手机号码用户']);
        }
        //=============================================
        $res = Db::table('up_phonecode')
            ->where('phone',$phone)
            ->order('time2 desc')
            ->limit(1)
            ->find();
        //=============================================================
        if($code != $res['code']){
            return json(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 901){
            return json(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json(['status'=>23,'msg'=>'验证码已使用']);
        }
        //TODO 修改密码成功后如果直接登录那么就要更新token
        $token = md5(date('YmdHis').rand(100000,999999));
        $update = array();
        $update['user_password'] = md5($newpass);
        if($type == 1){//修改后直接登录
            $update['user_token'] = $token;
        }
        $res = Db::table('up_u_user')->where('user_phone',$phone)->update($update);
        Db::table('up_phonecode')->where('id',$res['id'])->update(['status'=>1]);
        if($res){
            $user = Db::table('up_u_user')->where('user_phone',$phone)->find();
            return json(['status'=>200,'msg'=>$user]);
        }else{
            return json(['status'=>3,'msg'=>'密码重置失败']);
        }
    }
    
    /**
     * 更换手机号——1：给旧手机发送验证码  验证手机号
     * 参数： phone，code
     * @return string
     */
    public function changephone_old_yzm()
    {
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            return json_encode(['status'=>3,'msg'=>'没有此手机号码用户']);
        }
        //=============================================
        $res = Db::table('up_phonecode')
            ->where('phone',$phone)
            ->order('time2 desc')
            ->limit(1)
            ->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 901){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        return json_encode(['status'=>200,'msg'=>'ok']);
    }
    
    /**
     * 更换手机号——2：提交新手机
     * 参数：phone，code
     * @return string
     */
    public function changephone_new_yzm()
    {
        $phone = trim($_POST['phone'],' ');
        $uid = $_POST['user_id'];
        $code = trim($_POST['code'],' ');
        if($phone == "" || $code == ""){
            return json_encode(['status'=>0,'msg'=>'手机号和验证码不能为空']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json_encode(['status'=>0,'msg'=>'已经有此手机号码用户']);
        }
        //=============================================================
        $res = Db::table('up_phonecode')
            ->where('phone',$phone)
            ->order('time2 desc')
            ->limit(1)
            ->find();
        //=============================================================
        if(empty($res)){
            return json_encode(['status'=>0,'msg'=>'不是同一个手机号']);
        }
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 901){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        $res2 = Db::table('up_u_user')->where('user_id',$uid)->update(['user_phone'=>$phone]);
        if($res2){
            $new = Db::table('up_u_user')->where('user_id',$uid)->find();
            return json_encode(['status'=>200,'msg'=>$new]);
        }else{
            return json_encode(['status'=>0,'msg'=>'更新失败']);
        }
    }
    
    /**
     * 绑定微信或||QQ||微博
     * user_id,wqtoken,name,image,type(1微信 2qq  3微博)
     */
    public  function weixinqq()
    {
        header("Access-Control-Allow-Origin:*");
        $user_id = $_POST['user_id'];
        $wqtoken = $_POST['wqtoken'];
        $type = $_POST['type'];
        if($type == 1){
            $field = '_wx_';
            $name = '微信';
        }elseif($type == 2){
            $field = '_qq_';
            $name = 'QQ';
        }else{
            $field = '_wb_';
            $name = '微博';
        }
        $have = Db::table('up_u_user')->where("user{$field}token", $wqtoken)->find();
        //第一次用微信绑定好了，第二次又用另一个微信绑定时判断（qq同理）
        if($have){
            $msg = '该' . $name . '账号已绑定其他帐号，换个' . $name . '号吧！';
            return json_encode(['status'=>0,'msg'=>$msg]);
        }
        //=========end==============
        $name = $_POST['name'];
        $image = $_POST['image'];
        $data = array();
        $data['user'.$field.'token'] = $wqtoken;
        $data['user'.$field.'nickname'] = $name;
        $data['user'.$field.'image'] = $image;
        $user = Db::table('up_u_user')->where('user_id', $user_id)->field('user_username,user_image')->find();
        if(!$user['user_username']){
            $data['user_username'] = $name;
        }
        if(!$user['user_image']){
            $data['user_image'] = $image;
        }
        $res = Db::table('up_u_user')->where('user_id', $user_id)->update($data);
        if($res){
            $user = Db::table('up_u_user')->where('user_id', $user_id)->find();
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>5,'msg'=>'生成登录数据失败']);
        }
    }
    
    /**
     * 解绑微信||QQ||微博
     * user_id,type(1微信 2qq 3微博)
     */
    public  function weixinqqdel()
    {
        header("Access-Control-Allow-Origin:*");
        $user_id = $_POST['user_id'];
        $type = $_POST['type'];
        if($type == 1){
            $field = '_wx_';
        }elseif($type == 2){
            $field = '_qq_';
        }else{
            $field = '_wb_';
        }
        $data = array();
        $data['user'.$field.'token'] = '';
        $data['user'.$field.'nickname'] = '';
        $data['user'.$field.'image'] = '';
        $res = Db::table('up_u_user')->where('user_id', $user_id)->update($data);
        if($res){
            $user = Db::table('up_u_user')->where('user_id', $user_id)->find();
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>5,'msg'=>'解绑失败']);
        }
    }

    /**
     * 手机登录或注册时发送的验证码
     * @return bool
     * 参数：phone type(1是登录和更换手机号(第一步) 2是注册和更换手机号(第二步) 3是忘记密码)
     * 返回值：0参数错误，1手机格式错误，21登录无此号，22注册有此号，3验证码发送失败，4返回md5加密验证码
     */
//    public  function getPhoneCode(){//echo 1;die;
//        header("Access-Control-Allow-Origin:*");
//        extract(input());
//        if(!isset($phone) || !isset($type)){
//            return json(['status'=>0,'msg'=>'参数错误']);
//        }
//        $num = GetRandCode();
//        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
//            return json(['status'=>1,'msg'=>'请填写正确的手机号码']);
//        }
//        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
//        if(empty($username) && $type==1){
//            return json(['status'=>21,'msg'=>'没有此手机号码用户']);
//        }
//        if(empty($username) && $type==3){
//            return json(['status'=>21,'msg'=>'没有此手机号码用户']);
//        }
//        if(!empty($username) && $type==2){
//            return json(['status'=>22,'msg'=>'已经有此手机号码用户']);
//        }
//        $sendres = YzxSms($phone,$num);
//        if($sendres['code'] != '00000'){
//            return json(['status'=>3,'msg'=>$sendres['msg']]);
//        }else {
//            //=============================
//            $isset = Db::table('up_phonecode')->where('phone', $phone)->find();
//            if ($isset) {
//                $res = Db::table('up_phonecode')->where('phone', $phone)->update(['code' => md5($num), 'time2' => time(), 'code' => 0]);
//            } else {
//                $res = Db::table('up_phonecode')->insert(['phone' => $phone, 'code' => md5($num), 'time2' => time()]);
//            }
//            if (!$res) {
//                return json(['status' => 31, 'msg' => '数据库操作失败']);
//            }
//            //===============================================
//            return json(['status' => 200, 'msg' => md5($num)]);
//        }
//    }


    /**
     * 注册
     * @return bool
     * 参数：phone,code,name,password,major
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，4有其他未填项，5插入登录表失败，200成功
     */

    public  function userReg(){
        header("Access-Control-Allow-Origin:*");
        extract (input());
        if(!isset($phone) || !isset($code)){
            return json(['status'=>0,'msg'=>'参数错误']);
        }
        if(!isset($pass)){
            return json(['status'=>0,'msg'=>'参数错误']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json(['status'=>3,'msg'=>'已经有此手机号码用户']);
        }
        if($pass=='' || $code==''){
            return json(['status'=>4,'msg'=>'有未填项，请检查']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 601){
            return json(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json(['status'=>23,'msg'=>'验证码已使用']);
        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $data = array();
        $data['user_password'] = md5($pass);
        $data['user_time'] = date('Y-m-d H:i:s');
        $data['user_time'] = date('Y-m-d');
        $data['user_token'] = $token;
        $data['user_phone'] = $phone;
        $data['user_attestation'] = 1;//未认证
        $data['user_username'] = '用户' . rand(100000,999999);//未认证
        $id = Db::name('u_user')->insertGetId($data);
        if($id){
            $user = Db::table('up_u_user')
                ->where('user_id',$id)
                ->find();
//            $rytoken = $this->rongyun($user['user_id'],$user['user_username'],$user['user_image']);
//            $user['rytoken'] = $rytoken['token'];
            return json(['status'=>200,'msg'=>$user]);
        }else{
            return json(['status'=>5,'msg'=>'生成登录数据失败']);
        }
    }

    //================第三方登录====================

    /**
     * 微信或者qq或者微博登录
     * wqtoken,type(1是微信，2是qq，3是微博)
     * @return string
     */
//    public  function wqLogin()
//    {
//        header("Access-Control-Allow-Origin:*");
//        extract(input());
//        if($type == 1){
//            $field = 'user_wx_token';
//        }elseif($type == 2){
//            $field = 'user_qq_token';
//        }else{
//            $field = 'user_wb_token';
//        }
//        $username = Db::table('up_u_user')->where($field, $wxtoken)->find();
//        if (!empty($username)) {
//            $token = md5(date('YmdHis') . rand(100000, 999999));
//            $res = Db::table('up_u_user')->where($field, $wxtoken)->update(['user_token' => $token]);
//            if ($res) {
//                //===禁用和启用====
//                if($username['user_status'] != 1){
//                    return json(['status' => 0, 'msg' => '对不起，您无权登录，请联系客服']);
//                }
//                //======end======
//                $user = Db::table('ew_u_user')->where($field, $wxtoken)->find();
//                return json(['status' => 200, 'msg' => $user]);
//            } else {
//                return json(['status' => 3, 'msg' => '数据库出错']);
//            }
//        }else{
//            return json(['status' => 4, 'msg' => '查无此人']);
//        }
//    }
    
    /**
     * 微信或者qq或者微博第一次登录
     * wqtoken，phone，code，name，image，type
     * @return string
     */
//    public  function wqFirstLogin()
//    {
//        header("Access-Control-Allow-Origin:*");
//        extract(input());
//        if($type == 1){
//            $field = '_wx_';
//        }elseif($type == 2){
//            $field = '_qq_';
//        }else{
//            $field = '_wb_';
//        }
//        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
//            return json(['status'=>1,'msg'=>'请填写正确的手机号码']);
//        }
//        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
//        if(!empty($username)){
//            return json(['status'=>3,'msg'=>'已经有此手机号码用户']);
//        }
//        if($code==''){
//            return json(['status'=>4,'msg'=>'请填写验证码']);
//        }
//        //=============================================
//        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
//        //=============================================================
//        if($code != $res['code']){
//            return json(['status'=>21,'msg'=>'验证码错误']);
//        }
//        $now = time();
//        if($now - $res['time2'] >= 901){
//            return json(['status'=>22,'msg'=>'验证码超时']);
//        }
//        if($res['code']==1){
//            return json(['status'=>23,'msg'=>'验证码已使用']);
//        }
//        $token = md5(date('YmdHis').rand(100000,999999));
//        $data = array();
//        $data['user_time'] = date('Y-m-d H:i:s');
//        $data['user_token'] = $token;
//        $data['user_phone'] = $phone;
//        $data['user'.$field.'token'] = $wqtoken;
//        $data['user'.$field.'nickname'] = $name;
//        $data['user'.$field.'image'] = $image;
//        $data['user_image'] = $image;//用户名字和头像同步一下
//        $data['user_username'] = $name;//
//        if($name == ''){
//            $data['user_username'] = '用户' . rand(100000,999999);//未认证
//        }
//        $id = Db::name('u_user')->insertGetId($data);
//        if($id){
//            $user = Db::table('up_u_user')
//                ->where('user_id',$id)
//                ->find();
//            Db::table('up_phonecode')->where('phone',$phone)->update(['code'=>1]);
//            return json(['status'=>200,'msg'=>$user]);
//        }else{
//            return json(['status'=>5,'msg'=>'生成登录数据失败']);
//        }
//    }
}